const mediasoup = require("mediasoup")
const crypto = require('crypto')
const config = require('./config')
const {Member} = require('./member')
const {v4: uuidv4} = require('uuid')
const {getSupportedRtpCapabilities} = require("mediasoup");
const logger = require("./logger")

/**
 * 房间信息操作，包括用户 数据流
 */
class Room {

    constructor(roomId) {
        this._roomId = roomId;
        this._members = new Map();
    }

    getRouterCapabilities(){
        return this._router.rtpCapabilities
    }

    async init(worker, rtcServer){
        this._worker = worker
        this._rtcServer = rtcServer
        await this.createRouter()
    }

    async createRouter() {
        // Router media codecs.
        const { mediaCodecs } = config.mediasoup.routerOptions;

        // Create a mediasoup Router.
        this._router = await this._worker.createRouter({ mediaCodecs });
    }


    async createTransport(peerId, numStreams, appData) {
        const transport  = await this._router.createWebRtcTransport({
            webRtcServer: this._rtcServer,
            enableSctp: true,
            numSctpStreams: numStreams,
            ...config.mediasoup.webRtcTransportOptions,
            appData
        })
        const member = this._members.get(peerId)
        if (member !== undefined) member.setTransport(transport)
        const transportInfo = member.getTransportById(transport.id)
        return transportInfo
    }

    pushMember(peerId, member) {
        this._members.set(peerId, member)
    }

    getMembers(){
        return this._members
    }

    /**
     * 过滤 peerId
     * @param peerId
     * @returns {Map<any, any>}
     */
    filterMembers(peerId){
        const members = new Map();
         this._members.forEach((member, id) => {
            if (id !== peerId) {
                members.set(id, member)
            }
        })
        return members
    }

    getMember(peerId){
        return this._members.get(peerId)
    }

    removeMember(peerId) {
        this._members.delete(peerId)
    }
}

module.exports = Room
